//! # 高级构建器核心实现
//! 
//! 本模块提供了RustCloud框架高级构建器的核心实现，支持插件化架构和复杂配置。

use crate::config::*;
use crate::framework::RustCloudFramework;
use crate::di::{DIContainer, ComponentMetadata, ComponentLifecycle};
use crate::lifecycle::{LifecycleManager, LifecycleComponent};
use crate::advanced_builder::traits::*;
use rustcloud_core::{ServiceResult, ServiceError};
use std::sync::Arc;
use std::collections::{HashMap, HashSet};

/// 高级构建器
pub struct AdvancedRustCloudBuilder {
    config: RustCloudConfig,
    di_container: DIContainer,
    lifecycle_manager: LifecycleManager,
    plugins: Vec<Box<dyn BuilderPlugin>>,
    validators: Vec<Box<dyn ConfigValidator>>,
    environment_adapters: HashMap<String, Box<dyn EnvironmentAdapter>>,
    build_hooks: Vec<Box<dyn BuildHook>>,
}

impl AdvancedRustCloudBuilder {
    /// 创建新的高级构建器
    pub fn new(service_name: &str) -> Self {
        let mut config = RustCloudConfig::default();
        config.service.name = service_name.to_string();
        
        Self {
            config,
            di_container: DIContainer::new(),
            lifecycle_manager: LifecycleManager::new(),
            plugins: Vec::new(),
            validators: Vec::new(),
            environment_adapters: HashMap::new(),
            build_hooks: Vec::new(),
        }
    }

    /// 从配置创建构建器
    pub fn from_config(config: RustCloudConfig) -> Self {
        Self {
            config,
            di_container: DIContainer::new(),
            lifecycle_manager: LifecycleManager::new(),
            plugins: Vec::new(),
            validators: Vec::new(),
            environment_adapters: HashMap::new(),
            build_hooks: Vec::new(),
        }
    }

    /// 配置服务信息
    pub fn service<F>(mut self, configure: F) -> Self 
    where
        F: FnOnce(&mut ServiceConfig),
    {
        configure(&mut self.config.service);
        self
    }

    /// 配置网络
    pub fn network<F>(mut self, configure: F) -> Self 
    where
        F: FnOnce(&mut NetworkConfig),
    {
        configure(&mut self.config.network);
        self
    }

    /// 配置监控
    pub fn monitoring<F>(mut self, configure: F) -> Self 
    where
        F: FnOnce(&mut MonitoringConfig),
    {
        configure(&mut self.config.monitoring);
        self
    }

    /// 配置组件
    pub fn components<F>(mut self, configure: F) -> Self 
    where
        F: FnOnce(&mut ComponentConfig),
    {
        configure(&mut self.config.components);
        self
    }

    /// 条件配置
    pub fn when<F>(self, condition: bool, configure: F) -> Self 
    where
        F: FnOnce(Self) -> Self,
    {
        if condition {
            configure(self)
        } else {
            self
        }
    }

    /// 环境特定配置
    pub fn for_environment(mut self, env: &str) -> Self {
        self.config.service.environment = env.to_string();
        self
    }

    /// 开发环境配置
    pub fn for_development(self) -> Self {
        self.for_environment("development")
            .when(true, |builder| {
                builder.monitoring(|m| {
                    m.logging.level = "debug".to_string();
                    m.metrics.enabled = true;
                    m.tracing.enabled = true;
                })
            })
    }

    /// 生产环境配置
    pub fn for_production(self) -> Self {
        self.for_environment("production")
            .when(true, |builder| {
                builder.monitoring(|m| {
                    m.logging.level = "info".to_string();
                    m.metrics.enabled = true;
                    m.tracing.sampling_rate = 0.1; // 10%采样
                })
            })
    }

    /// 测试环境配置
    pub fn for_testing(self) -> Self {
        self.for_environment("testing")
            .when(true, |builder| {
                builder.monitoring(|m| {
                    m.logging.level = "warn".to_string();
                    m.metrics.enabled = false;
                    m.tracing.enabled = false;
                })
            })
    }

    /// 启用指标收集
    pub fn enable_metrics(self) -> Self {
        self.monitoring(|m| m.metrics.enabled = true)
    }

    /// 启用分布式追踪
    pub fn enable_tracing(self) -> Self {
        self.monitoring(|m| m.tracing.enabled = true)
    }

    /// 启用网关
    pub fn enable_gateway(self, port: u16) -> Self {
        self.components(|c| {
            c.gateway = Some(GatewayConfig {
                enabled: true,
                port,
                routes: Vec::new(),
                middleware: MiddlewareConfig {
                    auth: None,
                    rate_limit: None,
                    cors: None,
                },
            });
        })
    }

    /// 添加路由
    pub fn add_route(mut self, path: &str, service: &str, methods: Vec<String>) -> Self {
        if let Some(ref mut gateway) = self.config.components.gateway {
            gateway.routes.push(RouteConfig {
                path: path.to_string(),
                service: service.to_string(),
                methods,
                weight: Some(1),
            });
        }
        self
    }

    /// 注册组件
    pub async fn register_component<T: 'static + Send + Sync>(
        mut self,
        name: &str,
        component: T,
        lifecycle: ComponentLifecycle,
    ) -> ServiceResult<Self> {
        let metadata = ComponentMetadata {
            name: name.to_string(),
            lifecycle,
            ..Default::default()
        };

        // 注册到DI容器
        self.di_container.register(
            metadata,
            crate::di::SimpleFactory::new(|_| {
                Box::pin(async move { Ok(Arc::new(component)) })
            }),
        ).await?;

        Ok(self)
    }

    /// 添加插件
    pub fn use_plugin(mut self, plugin: Box<dyn BuilderPlugin>) -> Self {
        self.plugins.push(plugin);
        self
    }

    /// 添加配置验证器
    pub fn add_validator(mut self, validator: Box<dyn ConfigValidator>) -> Self {
        self.validators.push(validator);
        self
    }

    /// 添加环境适配器
    pub fn add_environment_adapter(mut self, adapter: Box<dyn EnvironmentAdapter>) -> Self {
        let env = adapter.environment().to_string();
        self.environment_adapters.insert(env, adapter);
        self
    }

    /// 添加构建钩子
    pub fn add_build_hook(mut self, hook: Box<dyn BuildHook>) -> Self {
        self.build_hooks.push(hook);
        self
    }

    /// 从环境变量加载配置
    pub fn load_from_env(mut self) -> ServiceResult<Self> {
        self.config.merge_from_env()?;
        Ok(self)
    }

    /// 从文件加载配置
    pub async fn load_from_file(mut self, path: &str) -> ServiceResult<Self> {
        let file_config = RustCloudConfig::from_file(path).await?;
        self.config = self.merge_configs(self.config, file_config);
        Ok(self)
    }

    /// 合并配置
    fn merge_configs(&self, mut base: RustCloudConfig, other: RustCloudConfig) -> RustCloudConfig {
        // 这里实现配置合并逻辑
        // 优先使用other中的非默认值
        if other.service.name != "rustcloud-service" {
            base.service.name = other.service.name;
        }
        if other.service.version != "1.0.0" {
            base.service.version = other.service.version;
        }
        if other.network.port != 8080 {
            base.network.port = other.network.port;
        }
        // 更多合并逻辑...
        base
    }

    /// 应用插件
    async fn apply_plugins(&mut self) -> ServiceResult<()> {
        // 按优先级排序插件
        self.plugins.sort_by_key(|p| p.priority());
        
        // 检查插件依赖
        self.validate_plugin_dependencies()?;
        
        // 应用插件
        for plugin in &self.plugins {
            tracing::info!("应用插件: {}", plugin.name());
            plugin.apply(self).await?;
        }
        
        Ok(())
    }

    /// 验证插件依赖
    fn validate_plugin_dependencies(&self) -> ServiceResult<()> {
        let plugin_names: HashSet<String> = self.plugins.iter()
            .map(|p| p.name().to_string())
            .collect();
            
        for plugin in &self.plugins {
            for dep in plugin.dependencies() {
                if !plugin_names.contains(&dep) {
                    return Err(ServiceError::ConfigError(format!(
                        "插件 {} 依赖的插件 {} 未找到", 
                        plugin.name(), 
                        dep
                    )));
                }
            }
        }
        
        Ok(())
    }

    /// 验证配置
    async fn validate_config(&self) -> ServiceResult<()> {
        // 基础配置验证
        self.config.validate()?;
        
        // 应用自定义验证器
        for validator in &self.validators {
            tracing::debug!("运行配置验证器: {}", validator.name());
            validator.validate(&self.config).await?;
        }
        
        Ok(())
    }

    /// 应用环境适配
    async fn apply_environment_adaptation(&mut self) -> ServiceResult<()> {
        let env = self.config.service.environment.clone();
        
        if let Some(adapter) = self.environment_adapters.get(&env) {
            tracing::info!("应用环境适配器: {}", env);
            adapter.adapt(&mut self.config).await?;
        }
        
        Ok(())
    }

    /// 构建框架
    pub async fn build(mut self) -> ServiceResult<RustCloudFramework> {
        tracing::info!("开始构建RustCloud框架: {}", self.config.service.name);
        
        // 执行构建前钩子
        for hook in &self.build_hooks {
            hook.before_build(&self).await?;
        }
        
        // 应用插件
        self.apply_plugins().await?;
        
        // 应用环境适配
        self.apply_environment_adaptation().await?;
        
        // 验证配置
        self.validate_config().await?;
        
        // 创建组件
        let registry = self.create_registry().await?;
        let load_balancer = self.create_load_balancer()?;
        let circuit_breaker = self.create_circuit_breaker()?;
        let metrics_collector = self.create_metrics_collector().await?;
        
        // 创建框架实例
        let framework = RustCloudFramework::new(
            self.config,
            registry,
            load_balancer,
            circuit_breaker,
            metrics_collector,
            HashMap::new(), // 自定义组件
        ).await?;
        
        // 执行构建后钩子
        for hook in &self.build_hooks {
            hook.after_build(&framework).await?;
        }
        
        tracing::info!("RustCloud框架构建完成");
        Ok(framework)
    }

    // 以下是组件创建方法的简化实现
    async fn create_registry(&self) -> ServiceResult<Arc<dyn rustcloud_registry::ServiceRegistry>> {
        // 实现注册中心创建逻辑
        Ok(Arc::new(rustcloud_registry::MemoryRegistry::new()))
    }

    fn create_load_balancer(&self) -> ServiceResult<Arc<dyn rustcloud_loadbalancer::LoadBalancerStrategy>> {
        // 实现负载均衡器创建逻辑
        Ok(Arc::new(rustcloud_loadbalancer::RoundRobinStrategy::new()))
    }

    fn create_circuit_breaker(&self) -> ServiceResult<Option<Arc<rustcloud_circuit_breaker::CircuitBreaker>>> {
        // 实现熔断器创建逻辑
        if self.config.components.circuit_breaker.enabled {
            let cb = rustcloud_circuit_breaker::CircuitBreaker::new(
                self.config.components.circuit_breaker.failure_threshold,
                self.config.components.circuit_breaker.success_threshold,
                std::time::Duration::from_millis(self.config.components.circuit_breaker.timeout_ms),
            );
            Ok(Some(Arc::new(cb)))
        } else {
            Ok(None)
        }
    }

    async fn create_metrics_collector(&self) -> ServiceResult<Option<Arc<dyn rustcloud_metrics::MetricsCollector>>> {
        // 实现指标收集器创建逻辑
        if self.config.monitoring.metrics.enabled {
            Ok(Some(Arc::new(rustcloud_metrics::MemoryMetricsCollector::new())))
        } else {
            Ok(None)
        }
    }
}